<?php
	class Router
	{
		private $_registry;
		private $_path;
		private $_args = array();
		
		function __construct($registry) 
		{
			$this->_registry = $registry;
		}
		
		// Set Path for the router
		function setPath($path) 
		{
			$path = trim($path, '/\\');
			$path .= DS;
			if (is_dir($path) == false) {
				throw new Exception ('Invalid controller path: `' . $path . '`');
			}
			
			$this->_path = $path;
		}
		
		// Here is the main function of router . Analyze the route from request and call the right controller for it
		function delegate() 
		{
			// Analyze route
			$this->getController($file, $controller, $action, $args);
            
            //Get name of controller and action
            $controller_name= $controller;
            $action_name=$action;
			// File available?
			if (is_readable($file) == false) {
				die ('404 Not Found');
			}
			// Include the file
			include ($file);
			// Initiate the class
			$class = 'Controller_' . $controller;
			$controller = new $class($this->_registry);
			// Action available?
			if (is_callable(array($controller, $action)) == false) {
				die ('404 Not Found');
			}
            
            $sess= new session();
            if($controller_name!='auth')
            {
                if(($sess->get_var('user_id')==null)||(($sess->get_var('user_id')!=null)&&($sess->get_var('user_id')<0)))
                {
                    header('Location: '.BASEURL.'/auth/login');
                }
            }
			
			// Run action
			$controller->$action($args);
		}

		// Method to get the right controller for the request
		private function getController(&$file, &$controller, &$action, &$args) 
		{
			$route = (empty($_GET['route'])) ? '' : $_GET['route'];
			
			if (empty($route)) { 
				$route = 'index'; 
			}
			// Get separate parts
			$route = trim($route, '/\\');
			$parts = explode('/', $route);
			// Find right controller
			$cmd_path = $this->_path;
			
			foreach ($parts as $part) {
				$fullpath = $cmd_path . $part;
				// Is there a dir with this path?
				if (is_dir($fullpath)) {
					$cmd_path .= $part . DS;
					array_shift($parts);
					continue;
				}
				// Find the file
				if (is_file($fullpath . '.php')) {
					$controller = $part;
				}
				array_shift($parts);
				break;
			}
			
			if (empty($controller)) { 
				$controller = 'index'; 
			};
			// Get action
			$action = array_shift($parts);
			if (empty($action)) { 
				$action = 'index'; 
			}
			$file = $cmd_path . $controller . '.php';
			$args = $parts;
		}	
	}
?>